package com.gzpi.hwgggh.service.impl;

import com.alibaba.fastjson.JSON;
import com.gzpi.hwgggh.entity.*;
import com.gzpi.hwgggh.mapper.*;
import com.gzpi.hwgggh.service.DWXService;
import com.gzpi.hwgggh.sysenum.EnumErrorCode;
import com.gzpi.hwgggh.utils.*;
import com.gzpi.hwgggh.vo.ExportConditionVo;
import javafx.beans.binding.ObjectExpression;
import net.lingala.zip4j.core.ZipFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @date : 2020-12-21 17:22
 **/
@Service
@Transactional
public class DWXServiceImpl implements DWXService {

    @Autowired
    private DWXMapper dwxMapper;
    @Autowired
    private DWGMapper dwgMapper;
    @Autowired
    private DWCMapper dwcMapper;
    @Autowired
    private GGPMapper ggpMapper;
    @Autowired
    private DWTPMapper dwtpMapper;
    @Autowired
    private DWFJMapper dwfjMapper;

    @Override
    public Result deleteDWX(String dwbhs,HttpServletRequest request) throws Exception {
        if (StringUtils.isNotBlank(dwbhs)){
            ExportConditionVo exportConditionVo = new ExportConditionVo();
            exportConditionVo.setDwbhs(dwbhs);
            List<DWX> dwxes = dwxMapper.selectDWXGListBandGgpXGListAndDwtpByVo(exportConditionVo);
            if (dwxes!=null && dwxes.size()>0){
                for (DWX dwx : dwxes) {
                    delete(dwx, request);//删除
                }
                return Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("删除{"+dwbhs+"}成功"));
            }
        }
        return Result.createError("删除失败");
    }

    public void delete(DWX dwx,HttpServletRequest request) throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("FID",dwx.getID());
        DWC dwc = dwcMapper.selectDWCBandGgpCListAndDwtpByMap(map);
        if (dwc!=null){
            dwcMapper.deleteDWCById(dwc.getID());//删除拆除点位
            ggpMapper.deleteGGPByFid(dwc.getID(),"GGP_X");//删除拆除广告牌信息
        }
        if (dwx.getDwg()!=null){
            dwgMapper.deleteDWGById(dwx.getDwg().getID());//删除规划点位
            ggpMapper.deleteGGPByFid(dwx.getDwg().getID(),"GGP_G");//删除规划广告牌信息
        }
        dwxMapper.deleteDWXById(dwx.getID());//删除现状点位
        ggpMapper.deleteGGPByFid(dwx.getID(),"GGP_X");//删除现状广告牌信息
        DWTP dwtp = null;
        if (dwx.getDwtp()!=null){
            dwtp = dwx.getDwtp();
            dwtpMapper.deleteDWTPById(dwx.getDwtp().getID());
        }

        DWFJ dwfj = dwfjMapper.selectDWFJBandSzrXGListByMap(map);
        if (dwfj!=null) {
            map.put("FID", dwfj.getID());
            dwfjMapper.deleteSZRG(map);

            dwfjMapper.deleteSZRX(map);

            map.put("ID", dwfj.getID());
            dwfjMapper.deleteDWFJ(map);
        }
        if (dwtp!=null) {
            String dirName = getDirName(dwtp.getXZQJT());
            if (dirName != null) {//删除现状全景
                FileUtil.deleteDir(dirName, HwggConstants.SAVE_PATH + "720全景/现状/");
            }
            dirName = getDirName(dwtp.getGHQJT());
            if (dirName != null) {//删除规划全景
                FileUtil.deleteDir(dirName, HwggConstants.SAVE_PATH + "720全景/规划/");
            }
            dirName = getDirName(dwtp.getCCQJT());
            if (dirName != null) {//删除拆除全景
                FileUtil.deleteDir(dirName, HwggConstants.SAVE_PATH + "720全景/拆除/");
            }
        }
        FileUtil.deleteDir(dwx.getID(), HwggConstants.SAVE_PATH);//删除图片和附件
    }



    public String getDirName(String url){
        if (StringUtils.isNotBlank(url)){
            String[] split = url.split("/");
            return split[3];
        }
        return null;
    }

    @Override
    public Result deleteDWXByID(String id, HttpServletRequest request) throws Exception{
        if (StringUtils.isNotBlank(id)) {
            Map<String,Object> map = new HashMap<>();
            map.put("ID",id);
            DWX dwx = dwxMapper.selectDWXGBandGgpXGListAndDwtpByMap(map); //获取点位信息
            if (dwx!=null){

                delete(dwx, request);//删除
                if (dwx.getXH()!=null){
                    updateXH(dwx.getXSDWBH());//重置编号
                }else{
                    updateDWBH(dwx.getXSDWBH());//重置点位序号
                }

                return Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("删除成功"));
            }
            return Result.createError(EnumErrorCode.ERROR_OBJECT_SEARCH.toString("找不到此信息"));
        }
        return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("参数不能为空"));
    }

    public void updateXH(String dwbh){
        Map<String,Object> map = new HashMap<>();
        map.put("DWBH",dwbh);
        List<DWX> dwxes = dwxMapper.selectDWXListByMap(map); //获取同编号最新序号
        if (dwxes!=null && dwxes.size()>0){
            if (dwxes.size()==1){
                dwxes.get(0).setXH("");
            }else{
                for (int i = 0 ; i < dwxes.size() ; i++){
                    dwxes.get(i).setXH((i+1)+"");
                }
            }
            for (DWX uDwx : dwxes) {
                dwxMapper.updateDWX(uDwx);
            }
        }
    }

    public void updateDWBH(String dwbh){
        String ldbh = dwbh.substring(0, dwbh.length() - 2);
        String xh = dwbh.substring(dwbh.length() - 2);
        List<DWX> dwxes = dwxMapper.selectDWXListByLdbh(ldbh, xh);
        for (DWX dwx : dwxes) {
            String xsdwbh = dwx.getXSDWBH();
            String xzldbh = xsdwbh.substring(0, xsdwbh.length() - 2);
            int xzxh = Integer.valueOf(xsdwbh.substring(xsdwbh.length() - 2));
            xzxh--;
            if (xzxh<10){
                dwx.setXSDWBH(xzldbh+"0"+xzxh);
            }else{
                dwx.setXSDWBH(xzldbh+xzxh);
            }
            dwxMapper.updateDWX(dwx);
        }
        List<DWC> dwcs = dwcMapper.selectDWCListByLdbh(ldbh, xh);
        for (DWC dwc : dwcs) {
            String xsdwbh = dwc.getDWBH();
            String ccldbh = xsdwbh.substring(0, xsdwbh.length() - 2);
            int ccxh = Integer.valueOf(xsdwbh.substring(xsdwbh.length() - 2));
            ccxh--;
            if (ccxh<10){
                dwc.setDWBH(ccldbh+"0"+ccxh);
            }else{
                dwc.setDWBH(ccldbh+ccxh);
            }
            dwcMapper.updateDWC(dwc);
        }
    }

    @Override
    public Result insertDW(String data, MultipartFile[] files, HttpServletRequest request) throws Exception{
        if (StringUtils.isNotBlank(data)){
            DWX dwx = JSON.parseObject(data, DWX.class);
            String dwxid = CommonTools.getCurrentTimeMillis();
            String dwtpid = CommonTools.getCurrentTimeMillis();
            DWX orDWx = dwxMapper.selectDWXByDwbh(new HashMap<String,Object>(){{
                put("DWBH",dwx.getXSDWBH());
            }});
            dwx.setCTIME(CommonTools.getCurrentTime());
            dwx.setID(dwxid);
            if (orDWx!=null){
                dwx.setUID(orDWx.getUID()!=null?orDWx.getUID():dwx.getID());
                dwx.setPXID(orDWx.getPXID());
            }
            if (dwxMapper.insertDWX(dwx)>0) {//保存现状点信息
                DWG dwg = dwx.getDwg();
                dwg.setID(CommonTools.getCurrentTimeMillis());
                dwg.setDWX(dwx);
                dwgMapper.insertDWG(dwg);//保存规划点信息

                updateXH(dwx.getXSDWBH());//重置序号

                DWTP dwtp = dwx.getDwtp()!=null?dwx.getDwtp():new DWTP();
                if (files!=null){
                    List<String> fileType = new ArrayList(){{
                       add("application/x-rar-compressed");
                       add("application/zip");
                    }};
                    for (MultipartFile file : files) { //编辑文件集合
                        String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
                        String savePath = "";//保存物理路径
                        String mappingUrl = "";//映射路径
                        String newFileName = "";//保存的文件名
                        boolean isZip = false;//是否是压缩包
                        if (fileType.contains(file.getContentType())){
                            String qz = fileName.substring(0,fileName.indexOf("_")+1);
                            if ("X_".equals(qz)){
                                savePath = HwggConstants.SAVE_PATH + "720全景/现状";
                                mappingUrl = HwggConstants.MAPPING_PATH + "720全景/现状";
                            }else if ("G_".equals(qz)){
                                savePath = HwggConstants.SAVE_PATH + "720全景/规划";
                                mappingUrl = HwggConstants.MAPPING_PATH + "720全景/规划";
                            }else if ("C_".equals(qz)){
                                savePath = HwggConstants.SAVE_PATH + "720全景/拆除";
                                mappingUrl = HwggConstants.MAPPING_PATH + "720全景/拆除";
                            }
                            newFileName = fileName.substring(fileName.indexOf("_") + 1);
                            isZip = true;
                        }else{
                            savePath = HwggConstants.SAVE_PATH + dwxid;
                            mappingUrl = HwggConstants.MAPPING_PATH + dwxid;
                            newFileName = fileName.substring(0,fileName.indexOf("_")+1) + dwx.getID();
                        }
                        //保存文件
                        FileResult fileResult = FileUtil.saveFileToPath(request, file, savePath, mappingUrl,newFileName);
                        if (!fileResult.isFlag()){
                            throw new RuntimeException("保存文件失败!");
                        }
                        if (isZip){//判断是否是压缩包
                            String httpUrl = fileResult.getHttpUrl();//访问路径
                            String name = fileResult.getFileName();//文件名
                            ZipFile zipFile = new ZipFile(fileResult.getFile());//
                            zipFile.setFileNameCharset("UTF-8");//字符集
                            if(savePath.startsWith("file:///")){
                                savePath=savePath.substring("file:///".length());
                            }
//                            File file1 = new File(savePath+"/"+name.substring(0,name.lastIndexOf(".")));
                            zipFile.extractAll(savePath+"/"+name.substring(0,name.lastIndexOf(".")));//解压文件

                            String path = httpUrl.substring(0,httpUrl.lastIndexOf("."))+"/vtour";//全景访问路径
                            if (fileResult.getHttpUrl().contains("现状")){
                                dwtp.setXZQJT(path);
                            }else if (fileResult.getHttpUrl().contains("规划")){
                                dwtp.setGHQJT(path);
                            }else if (fileResult.getHttpUrl().contains("拆除")){
                                dwtp.setCCQJT(path);
                            }
                            FileUtil.deleteFile(request,name,"file:///"+savePath);//删除压缩包
                        }
                        //根据文件名前缀保存到对应字段
                        switch (fileResult.getFileName().substring(0,fileResult.getFileName().indexOf("_")+1)){
                            case "GHT_":
                                dwtp.setGHT(fileResult.getHttpUrl());
                                break;
                            case "GHTR_":
                                dwtp.setGHTR(fileResult.getHttpUrl());
                                break;
                            case "GHTY_":
                                dwtp.setGHTY(fileResult.getHttpUrl());
                                break;
                            case "QWT_":
                                dwtp.setQWT(fileResult.getHttpUrl());
                                break;
                            case "XZT_":
                                dwtp.setXZT(fileResult.getHttpUrl());
                                break;
                        }
                    }
                }

                dwtp.setID(CommonTools.getCurrentTimeMillis());
                dwtp.setFID(dwxid);
                dwtpMapper.insertDWTP(dwtp);//保存点位图片信息

                return Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("新增成功"));
            }
            return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("新增失败"));
        }
        return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("参数不能为空"));
    }

    @Override
    public Result uploadCropped(String id, MultipartFile file, HttpServletRequest request) throws Exception {
        if (StringUtils.isNotBlank(id)&&file!=null){
            Map<String, Object> map = new HashMap<>();
            map.put("FID",id);
            DWTP dwtp = dwtpMapper.selectDWTPbyMap(map);
            if (dwtp==null) dwtp = new DWTP();
            CommonTools.uploadFile(file,dwtp,id,request);
            if (dwtp.getID()==null){
                dwtp.setID(CommonTools.getCurrentTimeMillis());
                dwtp.setFID(id);
                dwtpMapper.insertDWTP(dwtp);
            }else{
                dwtpMapper.updateDWTP(dwtp);
            }
            return Result.createSuccess(EnumErrorCode.SUCCESS_MESSAGE.toString("保存成功"));
        }
        return Result.createError(EnumErrorCode.ERROR_MESSAGE.toString("参数不能为空"));
    }
}
